import React, { Component, createRef } from 'react'
import { Table, Pagination, Input, Button, Modal, message } from 'antd'; // 引入表格控件
import { post } from '../../lib' // 引入lib
import styles from './index.module.css' // 把css引入当成变量
import Detail from './Detail' // 详情弹窗
import ImportExcel from './ImportExcel' // 导入excel的弹窗
import * as XLSX from 'xlsx'; // 导入excel的方法
const { Search } = Input;

export default class Member extends Component {
  state = {
    list: [], // 列表
    pageNo: 0, // 页号
    pageSize: 5,// 页距
    total: 0, // 总数
    keyword: '', // 搜索关键字
  }
  // 定义变量
  detailRef = createRef(); // 创建一个详情弹窗的引用
  excelRef = createRef(); // 创建一个导入excel

  componentDidMount() { // 挂载阶段初始化
    this.getList();
  }

  refreshList = () => { // 刷新列表
    this.setState({
      pageNo: 0,
      list: [],
    }, this.getList);
  }

  getList = async () => { // 获取列表
    const { pageNo, pageSize, keyword } = this.state;
    const data = await post('/list/member', {
      pageNo,
      pageSize,
      search: { 'name|phone': `/${keyword}/` }, // 名字或电话号码包含keyword
    });
    if (data.success) {
      let list = data.result.list;
      list = list.map(o => ({ ...o, key: o.id })); // 追加一个key值
      this.setState({ list, total: data.result.total });
    }
  }

  onPageChange = (page, pageSize) => {
    this.setState({ pageNo: page - 1 }, () => { // 只有再回调中pageNo才是改变后的值
      this.getList();
    });
  }

  onSearch = (value) => { // 搜索
    this.setState({ pageNo: 0, keyword: value}, ()=>{
      this.getList();
    }); // 页数重置
  }

  showCreate = () => { // 显示新增的弹窗
    this.detailRef.current.show();
  }

  showModify = (record) => { // 显示修改的弹窗
    this.detailRef.current.show(record);
  }

  deleteRow = (record) => { // 删除行
    Modal.confirm({
      content: '你是否确定要删除该数据吗?',
      onOk: async () => {
        const data = await post('/remove/member', { id: record.id });
        if (!data.success) {
          return Modal.error({ content: data.message });
        }
        // 刷新列表
        this.refreshList();
        message.success(`删除成功`);
      },
    });
  }

  exportExcel = () => { // 导出excel
    let { list } = this.state; // 列表数据
    list = list.map(o => ({
      '姓名': o.name,
      '手机号码': o.phone,
      '性别': o.gender,
      '密码': o.password,
    }));
    /* 将JSON数据转化为工作簿 */
    const worksheet = XLSX.utils.json_to_sheet(list);
    /* 生成Excel文件 */
    const workbook = XLSX.utils.book_new();
    /* 将工作簿添加到工作簿集合中 */
    XLSX.utils.book_append_sheet(workbook, worksheet, '人员表');
    /* 导出Excel文件 */
    XLSX.writeFile(workbook, '人员表.xlsx');
  }

  render() {
    const columns = [
      {
        title: '头像', // 标题文字
        dataIndex: 'head', // 字段名称
        key: 'head', // 唯一值
        render: data => <img className={styles.head} src={data} />,
      },
      {
        title: '姓名', // 标题文字
        dataIndex: 'name', // 字段名称
        key: 'name', // 唯一值
      },
      {
        title: '手机号码',
        dataIndex: 'phone',
        key: 'phone',
      },
      {
        title: '性别',
        dataIndex: 'gender',
        key: 'gender',
        // data:就是dataIndex对应的值, record是这一行的值，index：序号
        render: (data, record, index) => <div style={{ color: 'red' }}>{data}</div>
      },
      {
        title: '操作',
        key: 'oper',
        render: (data, record, index) => (
          <div className={styles.row}>
            <Button type="primary" onClick={() => this.showModify(record)}>修改</Button>
            <Button type="primary" danger onClick={() => this.deleteRow(record)}>删除</Button>
          </div>
        )
      },
    ];
    const { list, pageNo, pageSize, total } = this.state;
    return (
      <div>
        <div className={styles.top}>
          <Search placeholder="请输入关键字搜索" onSearch={this.onSearch} style={{ width: 200 }} />
          <div>
            <Button type="primary" onClick={this.showCreate}>新增</Button >
            <Button type="primary" style={{ margin: '0px 10px' }} onClick={() => this.excelRef.current.show()}>导入Excel</Button >
            <Button type="primary" onClick={this.exportExcel}>导出Excel</Button >
          </div>
        </div >
        <Table dataSource={list} columns={columns} pagination={false}></Table>
        <div className={styles.bottom}>
          <Pagination current={pageNo + 1} pageSize={pageSize} total={total} onChange={this.onPageChange} />
        </div>
        {/* 传一个方法给子组件刷新列表 */}
        <Detail ref={this.detailRef} refreshList={this.refreshList}></Detail>
        <ImportExcel ref={this.excelRef} refreshList={this.refreshList}></ImportExcel>
      </div >
    )
  }
}
